
clear all
set more off
set maxvar 20000
 
cd /data2/cedsei/firm/

/* Inputs */ 

local in_ana   "/data2/cedsei/firm/ana_panel_20230608.dta"

/* Outputs */

********************************************************************************

clear 
use "`in_ana'"

gen fsize_rams = n_nonnot + n_not
gen l_rev = log(sales_fek_w05)
drop if mi(l_rev)

bys lopnr_peorgnr (year): gen year_l1 = year[_n-1]
bys lopnr_peorgnr (year): gen year_l2 = year[_n-2]
bys lopnr_peorgnr (year): gen chi_l1 = chi[_n-1] if year==year_l1+1 & !mi(year_l1)
bys lopnr_peorgnr (year): gen chi_l2 = chi[_n-2] if year==year_l2+2 & !mi(year_l2)

gen event = cond(!mi(chi_l2) & !mi(chi_l1),cond(chi>0 & chi_l1==0 & chi_l2==0,1,0),0)
egen totevent = total(event), by(lopnr_peorgnr)
sum totevent, d
local rr=r(max)
drop if totevent==0
drop totevent 

gen eventorder = 0 
foreach num of numlist 1(1)`rr' {
	if `num'==1 {
		gen temp = year if event==1 
	}
	else {
		gen temp = year if event==1 & year>t1 
		drop t1
	}
	egen t1 = min(temp),by(lopnr_peorgnr)
	replace eventorder = `num' if year<=t1 & eventorder==0 & !mi(t1)
	drop temp 
}
tab eventorder
drop t1 

	sum year, d
	local rr = r(max)
foreach num of numlist 1(1)3 {
	bys lopnr_peorgnr (year): gen year_f`num' = year[_n+`num']
	gen alive_f`num' = cond(!mi(year_f`num'),cond(year_f`num'==year+`num',1,0),0)
	tab year alive_f`num' 
	replace alive_f`num' = . if year > `rr'-`num'
}

order event eventorder alive_f*, after(n_not)
drop if eventorder==0 

egen x = group(lopnr_peorgnr eventorder)

gen temp = year if event == 1 
egen nyear = min(temp), by(x)
gen  evyear = year - nyear
drop temp
order x nyear evyear, after(lopnr_peorgnr)

// Event-specific variables: 

foreach var of varlist  s monthnot n_not cumten age n_nonnot wchi chi wchi_df chi_df ///
wchi_dj chi_dj wchi_djl chi_djl bransch_sni2007 {
	gen temp = `var' if event==1 
	egen mtem = max(temp), by(x)
	replace `var' = mtem 
	drop mtem temp	
}

gen temp = l_rev if inrange(evyear,-3,-1)
egen l_rev_pre = mean(temp),by(x)
drop temp 

gen temp = l_rev - l_mon  if inrange(evyear,-3,-1)
egen prod_pre = mean(temp),by(x)
drop temp 

gen firmsize = n_not + n_nonnot

order x lopnr_peorgnr year nyear evyear l_rev l_rev_pre prod_pre chi s monthnot n_not cumten age n_nonnot chi_df ///
chi_dj chi_djl bransch_sni2007 firmsize fsize_rams

save event_panel_v2_20230608, replace 



















